<script setup lang="ts">
import { ref } from 'vue'
import UserCard from '../components/UserCard.vue'
import Counter from '../components/Counter.vue'

// 用于演示组件引用
const counterRef = ref<InstanceType<typeof Counter> | null>(null)

const users = [
  { name: '张三', title: '前端工程师', userId: 1 },
  { name: '李四', title: '后端工程师', userId: 2 },
  { name: '王五', title: '产品经理', userId: 3 }
]

const handleUserSelect = (userId: number) => {
  console.log('选中用户:', userId)
}

const handleClick = () => {
  // 通过 ref 访问子组件
  counterRef.value?.increment()
}
</script>

<template>
  <div class="components-demo">
    <h2>组件示例</h2>

    <section>
      <h3>1. 基础组件 Props & Events</h3>
      <div class="user-list">
        <UserCard
          v-for="user in users"
          :key="user.name"
          v-bind="user"
          @select="handleUserSelect"
        />
      </div>
    </section>

    <section>
      <h3>2. 组件引用</h3>
      <div class="counter-demo">
        <Counter ref="counterRef" :initial="10" />
        <button @click="handleClick">
          通过父组件增加计数
        </button>
      </div>
    </section>

    <section>
      <h3>3. 插槽示例</h3>
      <div class="slot-demo">
        <!-- 默认插槽 -->
        <UserCard name="默认插槽" title="示例">
          <p>这是默认插槽内容1</p>
        </UserCard>

        <!-- 具名插槽 -->
        <UserCard name="具名插槽" title="示例">
          <template #title>
            <h4>自定义标题</h4>
          </template>
          <template #default>
            <p>默认插槽内容</p>
          </template>
        </UserCard>
      </div>
    </section>
  </div>
</template>

<style scoped>
.components-demo {
  padding: 20px;
}

section {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.user-list {
  display: grid;
  gap: 1rem;
}

.counter-demo {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.slot-demo {
  display: grid;
  gap: 1rem;
}
</style> 